package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MykafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 *
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
/*        env.enableCheckpointing(10 * 1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 3000L));
        env.setStateBackend(new FsStateBackend("hfds://hadoop102:8020/CK"));
        System.setProperty("HADOOP_USER_NAME", "atguigu");*/
        // TODO: 3. 从kafka中读取数据
        String topic = "dwd_page_log";
        String groupId = "user_jump_aap_groupId";
        String sinkTopic = "dwm_user_jump_detail";

        DataStream<String> kafkaDS = env
                .fromElements(
                        "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000}",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"home\"},\"ts\":15000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"detail\"},\"ts\":30000} "
                );

//        DataStreamSource<String> kafkaDS = env.addSource(MykafkaUtil.getkafkaSource(topic, groupId));
        SingleOutputStreamOperator<JSONObject> JsonObjDS = kafkaDS.map(r -> JSON.parseObject(r));
        SingleOutputStreamOperator<JSONObject> jsonObjwithmarkDs = JsonObjDS.assignTimestampsAndWatermarks(
                WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject jsonObject, long recordTimestamp) {
                                return jsonObject.getLong("ts");
                            }
                        })
        );
        KeyedStream<JSONObject, String> keyedStream = jsonObjwithmarkDs.keyBy(r -> r.getJSONObject("common").getString("mid"));
        // TODO: 配置CEP匹配模式
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            return true;
                        }
                        return false;
                    }
                }
        ).next("second").where(
                new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        String PageId = jsonObject.getJSONObject("page").getString("page_id");
                        if (PageId != null && PageId.length() > 0) {
                            return true;
                        }
                        return false;
                    }
                }
        ).within(Time.seconds(10));
        // TODO: 将模式应用到流中
        PatternStream<JSONObject> filterDS = CEP.pattern(keyedStream, pattern);
        // TODO: 从流中提取超时数据
        // 8.1 定义侧输出标记(因为超时数据会放到输出流中)
        OutputTag<String> outputTag = new OutputTag<String>("outputTag") {
        };
        SingleOutputStreamOperator<String> resDS = filterDS.flatSelect(
                outputTag,
                new PatternFlatTimeoutFunction<JSONObject, String>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                        List<JSONObject> firstList = pattern.get("first");
                        // 在处理超时数据的时候,写到主流的数据，会打上侧输出流标记
                        for (JSONObject jsonObject : firstList) {
                            out.collect(jsonObject.toJSONString());
                        }
                    }
                },

                new PatternFlatSelectFunction<JSONObject, String>() {
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> pattern, Collector<String> out) throws Exception {
                        // 处理未超时的数据
                    }
                }
        );


// 8.3 获取侧输出流
        DataStream<String> jumpDS = resDS.getSideOutput(outputTag);
        jumpDS.print(">>>>");
// TODO: 9. 将跳出明细写到kafka的dwm层
        jumpDS.addSink(MykafkaUtil.getKafkaSink(sinkTopic));

        env.execute();
    }
}
